import Common from '../../common/common.js';
let common = new Common;
const app = getApp();
Page({
  data: {
    /**
     * 0 普通名片  
     * 1 25周年活动名片  
     * 2 元春活动名片   
     * 注意：1的名片样式不一样  2的二维码路径不一样
     */
    isSpecial: 0,
    currect: 1,
    currectChild: 0,
    imgUrl: common.imgUrl,
    imageShopUrl: '', //店铺海报图片
    catShopUrl: '', //名片海报
    background: '',
    width: 375,
    height: 677,
    isDisable: false, //防止多次点击
    doorwayPic: '',
    uuid: '',
    // backCardPic:'',
    // backgroundColor:'', //背景色
  },
  // 切换tab 
  changetab: function (e) {
    let currect = e.currentTarget.dataset.currect;
    if (currect == 2) { //
      common.showToast("该功能暂未开放")
      return
    }
    this.setData({
      currect,
      orgName: getApp().globalData.shopInfo.orgName
    })
  },
  // 切换子级tab
  chooseListChild(e) {
    this.setData({
      currectChild: e.currentTarget.dataset.id,
    })
    console.log(this.data.currectChild)
    this.data.list.forEach((item, index) => {
      if (this.data.currectChild == index) {
        this.setData({
          background: item.cardPic,
          fontColor: item.fontColor,
          uuid: item.uuid,
          isSpecial: Number(item.isSpecial)
        })
      }
    })
    this.getImageInfo(this.data.background) //获取背景图图片尺寸
  },
  onLoad: function (options) {
    this.setData({
      currect: options.currect,
      str: Math.random(),
      userId: getApp().globalData.userId,
      orgSeq: getApp().globalData.shopInfo.orgSeq
    })
    this.queryActivityUsaCard(); //获得背景图
    this.queryStoreCardConfig(); //获得头像 
  },
  getImageInfo(background) {
    wx.getImageInfo({
      src: background,
      success: (res) => {
        this.setData({
          width: res.width / 2,
          height: res.height / 2
        })
        console.log(this.data.width)
        console.log(this.data.height)
      }
    })
  },
  //获得背景
  queryActivityUsaCard() {
    let data = {}
    common.requestAjax('/api/user-service/v1/StoreCard/queryActivityUsaCard', 'get', data).then(res => {

      if (res.data.code == 1) {
        if (res.data.records && res.data.records.length != 0) {
          //去除：443
          res.data.records.forEach((item, index) => {
            item.cardPic = item.cardPic.replace(":443", '');
          })
          this.setData({
            list: res.data.records,
            background: res.data.records[0].cardPic,
            fontColor: res.data.records[0].fontColor,
            uuid: res.data.records[0].uuid,
            isSpecial: Number(res.data.records[0].isSpecial) || 0
          })
          console.log(this.data.background)
          this.getInfo();
        } else {
          wx.showToast({
            title: '暂无活动或活动已过期，即将返回上一页',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack({})
          }, 2000);
        }
      }
    }).catch(err => {
      console.log(err);
    })
  },
  getInfo: function () {
    let data = {
      userId: this.data.userId, //getApp().globalData.userId,
      orgSeq: this.data.orgSeq //getApp().globalData.shopInfo.orgSeq
    }
    common.requestAjax('/api/user-service/v1/foreign/getUserAndStoreInfo', 'GET', data).then(res => {
      this.setData({
        stroeInfo: res.data.storeInfoDTO,
        userInfo: res.data.userInfoDTO,
        background: this.data.background //背景图
      })
      //获取小程序码
      this.getWxCode();
      this.getImageInfo(this.data.background) //获取背景图图片尺寸
      // 头像截取
      let headerImg = this.data.userInfo.headPicUrl ? this.data.userInfo.headPicUrl.replace(":443", '') : '';
      this.setData({
        headerImg,
      })

    }).catch(err => {
      console.log(err);
    })
  },
  //获得背景图和背景色
  queryStoreCardConfig() {
    let data = {
      userId: this.data.userId, //getApp().globalData.userId,
      orgSeq: this.data.orgSeq //getApp().globalData.shopInfo.orgSeq
    }
    common.requestAjax('/api/user-service/v1/StoreCard/queryStoreCardConfig', 'POST', data).then(res => {
      if (res.data.code == 1) {
        let doorwayPic = res.data.result.headPicUrl || '';
        doorwayPic = doorwayPic.replace(':443', '');
        this.setData({
          doorwayPic, //门头照
          // backCardPic:res.data.result.cardPic.replace(':443',''),
          // backgroundColor:res.data.result.backgroundColor || 'white' ,
          //fontColor: res.data.result.fontColor || '#FFECCA'
        })
        console.log(this.data.background)
      }
    }).catch(err => {
      console.log(err);
    })
  },
  getWxCode() {
    let data = {
      type: this.data.isSpecial == 2 ? 4 : 1, //1活动分享   2商品分享 3 店铺分享  4 元春活动
      page: this.data.isSpecial == 2 ? "pages1/yuanSpringActivity/index" : "pages/shop/index", //元春活动调往不同页面
      //活动type==3 店铺type==4
      sceneStr: this.data.userId + ',' + this.data.orgSeq + ',' + 3,
      appid: getApp().globalData.appId,
      secret: getApp().globalData.wx_code,
      width: 300,
      userId: this.data.userId, //getApp().globalData.userId,
      orgSeq: this.data.orgSeq, //getApp().globalData.shopInfo.orgSeq
      phone: this.data.userInfo.tel
    }
    common.requestAjax('/api/file-service/v1/share/appletCode', 'POST', data).then(res => {
      if (res.data.code) {
        let wxCode = res.data.url.replace(":443", '');
        this.setData({
          wxCode,
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },

  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save()
    ctx.beginPath()
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore()
  },
  // 超出换行
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度防止文字重叠
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  //绘制名片
  canvasKapian() {
    if (app.globalData.openStatus == 0) {
      wx.showToast({
        title: '该店铺已歇业，无法保存图片',
        icon: 'none'
      })
      return;
    }
    if (!this.data.headerImg) {
      wx.showToast({
        title: '活动名片生成异常，请先维护名片头像!',
        icon: 'none'
      })
      return;
    }
    wx.getSetting({
      success: res => {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              this.canvasClick();
            },
            fail: err => {
              wx.showModal({
                title: "提示",
                content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          this.canvasClick();
                        } else {
                          wx.showToast({
                            title: '获取权限失败,无法使用保存图片或视频到您的相册',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        } else {
          this.canvasClick();
        }
      }
    })
  },
  canvasClick() {
    if (this.data.isSpecial == 1) { //特殊名片
      this.canvasClick1();
      return false
    }
    this.setData({
      isDisable: true
    })
    wx.showLoading({
      title: '活动生成中...',
    })

    let image1 = this.localImge(this.data.background);
    let image2 = this.localImge(this.data.wxCode);
    let image3 = this.localImge(this.data.headerImg || '');
    // let image4 = this.localImge(this.data.backCardPic);//名片背景图 
    Promise.all([image1, image2, image3]).then(res => {
      console.log(res);
      let background1 = res[0];
      let wxCode1 = res[1];
      let headerImg1 = res[2];
      // let cardBc1 = res[3]
      const ctx = wx.createCanvasContext("shareKapian");
      // this.data.backgroundColor ||
      ctx.setFillStyle('#ffffff'); //背景色
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      let top = 60;
      let left = 28;
      let x = this.data.width / 375
      console.log(x)
      ctx.fillStyle = this.data.fontColor || "#ffffff";
      // 封面图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);
      // 背景图卡片
      // ctx.drawImage(cardBc1, 10, 24, 355, 180); 
      // logo
      ctx.drawImage('../../images/index/logo.png', left * x, (top - 10) * x, 42 * x, 32 * x);
      // 店铺名称 
      ctx.setFontSize(15 * x);
      ctx.fillText(this.data.stroeInfo.storeName || '', 80 * x, top * x);
      // 店铺描述
      ctx.setFontSize(10 * x);
      this.drawText(ctx, this.data.stroeInfo.storeDesc || "", 80 * x, 80 * x, 389, 180)
      // 小程序码
      this.circleImg(ctx, wxCode1, 280 * x, (top - 20) * x, 35 * x, 35 * x)
      // 门头照
      this.circleImg(ctx, headerImg1, left * x, 120 * x, 22 * x)
      // 名字 店主||店长||店员
      ctx.setFontSize(18 * x);
      let member = ''
      if (this.data.userInfo.userType == 4) {
        member = '店主'
      } else if (this.data.userInfo.userType == 5) {
        member = '店长'
      } else if (this.data.userInfo.userType == 6) {
        member = '店员'
      }
      ctx.fillText(this.data.userInfo.realName + ' ' + member, 83 * x, 126 * x);
      // 电话图标 
      ctx.drawImage('../../images/icon/tel1.png', 83 * x, 138 * x, 10 * x, 10 * x);
      // 电话号码
      ctx.setFontSize(11 * x);
      ctx.fillText(this.data.userInfo.tel || '', 100 * x, 148 * x);
      // 地址图标
      ctx.drawImage('../../images/icon/adress.png', 83 * x, 156 * x, 10 * x, 10 * x);
      // 详细地址
      ctx.setFontSize(11 * x);
      console.log(this.data.stroeInfo.storeAddressDetail)
      if (this.data.stroeInfo.storeAddressDetail.length > 18) {
        let str1 = this.data.stroeInfo.storeAddressDetail.slice(0, 18);
        let str2 = this.data.stroeInfo.storeAddressDetail.slice(18);
        ctx.fillText(str1, 100 * x, 166 * x);
        ctx.fillText(str2, 100 * x, 166 * x + 15 * x);
      } else {
        ctx.fillText(this.data.stroeInfo.storeAddressDetail || '', 100 * x, 166 * x);
      }

      ctx.save()
      ctx.restore();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "shareKapian",
          success: res => {
            wx.hideLoading();
            this.setData({
              catShopUrl: res.tempFilePath
            });
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //特殊海报生成
  canvasClick1() {
    this.setData({
      isDisable: true
    })
    wx.showLoading({
      title: '活动生成中...',
    })
    let {
      storeName,
      storeDesc,
      storeAddressDetail
    } = this.data.stroeInfo;
    let {
      userType,
      realName,
      tel
    } = this.data.userInfo;
    let image1 = this.localImge(this.data.background);
    let image2 = this.localImge(this.data.wxCode);
    let image3 = this.localImge(this.data.headerImg || '');
    // let image4 = this.localImge(this.data.backCardPic);//名片背景图 
    Promise.all([image1, image2, image3]).then(res => {
      console.log(res);
      let background1 = res[0];
      let wxCode1 = res[1];
      // let cardBc1 = res[3]
      const ctx = wx.createCanvasContext("shareKapian");
      // this.data.backgroundColor ||
      ctx.setFillStyle('#ffffff'); //背景色
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      let x = this.data.width / 375
      console.log(x);
      ctx.setFillStyle("#FFE2A4");
      // 封面图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);
      // 背景图卡片
      // ctx.drawImage(cardBc1, 10, 24, 355, 180); 
      // logo
      ctx.drawImage('../../images/index/logo.png', 32 * x, 95 * x, 60 * x, 44 * x);

      //竖线
      ctx.fillRect(100 * x, 95 * x, 1 * x, 44 * x)

      // 店铺名称 
      ctx.setFontSize(15 * x);
      this.drawText(ctx, storeName || '', 110 * x, (95 + 15) * x, 389, 180)
      // 店铺描述
      ctx.setFontSize(13 * x);
      if (storeName.length > 12) {
        this.drawText(ctx, storeDesc || "", 110 * x, (95 + 32 + 18) * x, 389, 180)
      } else {
        this.drawText(ctx, storeDesc || "", 110 * x, (95 + 15 + 18) * x, 389, 180)
      }

      // 小程序码
      this.circleImg(ctx, wxCode1, 270 * x, 90 * x, 38 * x, 38 * x)

      // 名字 店主||店长||店员
      ctx.setFontSize(25 * x);
      ctx.setFillStyle('#ffffff');
      let member = ''
      if (userType == 4) {
        member = '店主'
      } else if (userType == 5) {
        member = '店长'
      } else if (userType == 6) {
        member = '店员'
      }

      realName = realName.slice(0, 1) + ' ' + realName.slice(1);
      ctx.fillText(realName, 32 * x, 200 * x);
      //职称
      ctx.setFontSize(14 * x);
      ctx.fillText('/' + member, realName.length * 25 * x + 20 * x, 200 * x);

      // 电话号码
      ctx.setFontSize(12 * x);
      ctx.fillText('Mob:' + tel || '', 180 * x, 190 * x);
      // 地址
      ctx.fillText('Add:', 180 * x, 205 * x);
      this.drawText(ctx, storeAddressDetail || "", 208 * x, 205 * x, 389, 140);

      // 详细地址
      // ctx.setFontSize(11 * x);
      // console.log(this.data.stroeInfo.storeAddressDetail)
      // if (this.data.stroeInfo.storeAddressDetail.length > 18) {
      //   let str1 = this.data.stroeInfo.storeAddressDetail.slice(0, 18);
      //   let str2 = this.data.stroeInfo.storeAddressDetail.slice(18);
      //   ctx.fillText(str1, 100 * x, 166 * x);
      //   ctx.fillText(str2, 100 * x, 166 * x + 15 * x);
      // } else {
      //   ctx.fillText(this.data.stroeInfo.storeAddressDetail || '', 100 * x, 166 * x);
      // }

      ctx.save()
      ctx.restore();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "shareKapian",
          success: res => {
            wx.hideLoading();
            this.setData({
              catShopUrl: res.tempFilePath
            });
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //生成本地图片
  localImge: function (src) {
    console.log('src', src);
    return new Promise(function (resolve, reject) {
      wx.downloadFile({
        url: src,
        success: function (res) {
          resolve(res.tempFilePath);
        },
        fail: err => {
          reject(err)
        }
      });
    });
  },
  //保存图片
  downFn() {
    let imgurl = '';
    wx.showLoading({
      title: '保存中...',
    })
    imgurl = this.data.catShopUrl;
    wx.saveImageToPhotosAlbum({
      filePath: imgurl,
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: "保存成功，从相册中分享到朋友圈吧",
          icon: "none",
          duration: 4000
        });
        this.setData({
          isDisable: false
        })
        this.addNum();
      },
      fail: function (err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          console.log(111111);
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log(res);
                  },
                })
              }
            }
          })
        }
      }
    });
  },
  addNum: function () {
    let data = {}
    common.requestAjax('/api/user-service/v1/storeDownloadCount/addCardAmount?orgSeq=' + this.data.orgSeq + '&type=' + 1 + '&cardId=' + this.data.uuid, 'POST').then(res => {}).catch(err => {
      console.log(err);
    })
  },
  /**
   * param {CanvasContext} ctx canvas上下文
   * param {number} x 圆角矩形选区的左上角 x坐标
   * param {number} y 圆角矩形选区的左上角 y坐标
   * param {number} w 圆角矩形选区的宽度
   * param {number} h 圆角矩形选区的高度
   * param {number} r 圆角的半径
   */
  roundRect(ctx, x, y, w, h, r) {
    // 开始绘制
    ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.setFillStyle('transparent')
    // ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)

    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
  },
  prewImage() {
    wx.previewImage({
      urls: [this.data.wxCode],
      complete: (res) => {},
      current: this.data.wxCode,
      fail: (res) => {},
      success: (res) => {},
    })
  }
})